package io.adrainty.bolee.framework.gateway.filter;

import io.adrainty.bolee.framework.gateway.decorator.CacheServerHttpRequestDecorator;
import io.adrainty.bolee.framework.gateway.properties.LogRecordProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/7/27 下午10:42
 */

@Component
public class RequestRecordFilter extends BaseFilter {

    private final LogRecordProperties properties;

    public RequestRecordFilter(@Autowired LogRecordProperties properties) {
        this.properties = properties;
    }

    @Override
    protected Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 需记录日志:对ServerHttpRequest进行二次封装，解决requestBody只能读取一次的问题
        CacheServerHttpRequestDecorator decorator = new CacheServerHttpRequestDecorator(exchange.getRequest());
        // 把当前的请求体进行改变，用于传递新放入的body
        return chain.filter(exchange.mutate().request(decorator).build());
    }

    @Override
    protected boolean isFilter(String path, boolean isUploadRequest, ServerHttpRequest request) {
        if (isUploadRequest) return false;
        return nonePathMatch(properties.getIgnoreUrl(), path);
    }


}
